//
//  MovieDetailVC.m
//  MovieDate
//
//  Created by 杨运涛 on 16/3/14.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "MovieDetailVC.h"
#import "PublishDateVC.h"
#import "MovieDetailCell.h"
#import "XYuser.h"
#import "DateDetailVC.h"
#import "EnumHeader.h"
@interface MovieDetailVC ()

@property (strong, nonatomic) IBOutlet UIImageView *pImgBg;

@property (weak, nonatomic) IBOutlet UILabel *movieTitleLB;
@property (weak, nonatomic) IBOutlet UILabel *movieMinuteTimeLB;
@property (weak, nonatomic) IBOutlet UILabel *movieTypeLB;
@property (weak, nonatomic) IBOutlet UILabel *meetPersonNumLB;
@property (weak, nonatomic) IBOutlet UIImageView *movieTitleImageView;
@property (weak, nonatomic) IBOutlet UILabel *introductionLB;
@property (weak, nonatomic) IBOutlet UIView *pView;

@property (nonatomic,strong) NSMutableArray *dataArr;

@property (weak, nonatomic) IBOutlet UIButton *popBtn;
@property (weak, nonatomic) IBOutlet UIView *instroduceView;
@property (weak, nonatomic) IBOutlet UIButton *showMoreBTN;

@end

@implementation MovieDetailVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self.pTableView.mj_header beginRefreshing];
}

- (void)initInfo
{
    [super initInfo];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self selDefaultNavigationBackground];
    [self initView];
    [self.pTableView setTableFooterView:[UIView new]];
    [SVProgressHUD show];
    [self initRequestData:1];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr ) {
        _dataArr = [NSMutableArray array];
    }
    return  _dataArr;
}

-(void)initView
{
     __weak typeof(self) weakSelf = self;
    [self.movieTitleImageView sd_setImageWithURL:[NSURL URLWithString:self.movie.moiveImage]];
    [self.movieTitleImageView.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.movieTitleImageView.layer setBorderWidth:2.0f];
    
    [self.pImgBg sd_setImageWithURL:[NSURL URLWithString:self.movie.moiveImage]];
    self.movieTitleLB.text = self.movie.moiveTitle;
    self.movieMinuteTimeLB.text = self.movie.moiveTime;
    self.introductionLB.text = self.movie.introduction;
    self.movieTypeLB.text = self.movie.moiveType;
    self.meetPersonNumLB.text = self.movie.appointmentCount;
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,self.pTableView.tableHeaderView.frame.size.height-30)];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [toolbar setTranslucent:YES];
    [toolbar setAlpha:0.95f];
    [self.pView insertSubview:toolbar aboveSubview:self.pImgBg];

    
    static int index = 1;
   
    [self.view bringSubviewToFront:weakSelf.popBtn];
        self.pTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        index = 1;
        [weakSelf initRequestDataDown:index];
    }];
    self.pTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        index++ ;
        [weakSelf initRequestData:[[NSString stringWithFormat:@"%d",index] integerValue]];
    }];
}

-(void)initRequestDataDown:(NSInteger )page
{
    __weak typeof(self) weakSelf = self;
    User *user =  [User defaultUser];
    NSString *curTimeStr = [user getCurTime]; //获取当前时间
   [TDNetwork requestMoviesListPOST:movieDetailListIP
                        andPage:page
                    andPageSize:5
                     andCurCity:user.pStrLocationAddress
                       andCurJd:user.pStrLongitude
                       andCurWd:user.pStrLatitude
                     andSexType:@"3"
                    andSortType:@"time"
                     andSortVal:@"asc"
                     andReqTime:curTimeStr
                     andMovieId:self.movie.movieId
                       complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
                           if (succeed) {
                                [weakSelf.dataArr removeAllObjects];
                                NSMutableArray *arr =  [dictionary valueForKey:@"res"];
                                [weakSelf.dataArr addObjectsFromArray:arr];
                
                               [weakSelf.pTableView reloadData];
                               [self.pTableView.mj_footer endRefreshing];
                               [self.pTableView.mj_header endRefreshing];
                           }else{
                           }
                       }];
}

-(void)initRequestData:(NSInteger )page{
    __weak typeof(self) weakSelf = self;
    User *user =  [User defaultUser];
    NSString *curTimeStr = [user getCurTime]; //获取当前时间
    [TDNetwork requestMoviesListPOST:movieDetailListIP
                             andPage:page
                         andPageSize:5
                          andCurCity:user.pStrLocationAddress
                            andCurJd:user.pStrLongitude
                            andCurWd:user.pStrLatitude
                          andSexType:@"3"
                         andSortType:@"time"
                          andSortVal:@"asc"
                          andReqTime:curTimeStr
                          andMovieId:self.movie.movieId
                            complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
                                if (succeed) {
                                    [SVProgressHUD dismiss];
                                    NSMutableArray *arr =  [dictionary valueForKey:@"res"];
                                    [weakSelf.dataArr addObjectsFromArray:arr];
                                    
                                    [weakSelf.pTableView reloadData];
                                    [self.pTableView.mj_footer endRefreshing];
                                    [self.pTableView.mj_header endRefreshing];
                                }else{
                                    [SVProgressHUD dismiss];
                                }
                            }];
}

- (IBAction)btnBuyAction:(UIButton *)sender {
    [SVProgressHUD showInfoWithStatus:@"暂未开放"];
}

- (IBAction)btnPopAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//显示更多介绍的事件
- (IBAction)showMoreIntroduAction:(id)sender {
    UIButton *btn = (UIButton *)sender;

    CGFloat headerheight  = self.pTableView.tableHeaderView.frame.size.height;
    CGFloat headerwight  = self.pTableView.tableHeaderView.frame.size.width;
    CGFloat headerLBx  = self.pTableView.tableHeaderView.frame.origin.x;
    CGFloat headerLBy  = self.pTableView.tableHeaderView.frame.origin.y;
    
    btn.selected=!btn.selected;//每次点击都改变按钮的状态
    if (btn.selected) {
                             UIView *view = self.pTableView.tableHeaderView;
                             view.frame =   CGRectMake(headerLBx, headerLBy, headerwight, headerheight+80);
                             [self.pTableView beginUpdates];
                             self.pTableView.tableHeaderView = view;
                             [self.pTableView endUpdates];
    }else{
                             UIView *view = self.pTableView.tableHeaderView;
                             view.frame =   CGRectMake(headerLBx, headerLBy, headerwight, headerheight-80);
                             [self.pTableView beginUpdates];
                             self.pTableView.tableHeaderView = view;
                             [self.pTableView endUpdates];
    }
}
- (IBAction)btnPublishDateAction:(id)sender {

    
    [self performSegueWithIdentifier:@"idfPublishDateVC" sender:self];
}
#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  MovieDetailCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"idfMovieDetailCell"];

    if (!cell) {
        cell = [[MovieDetailCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"idfMovieDetailCell"];
    }
   NSDictionary *dic =  [self.dataArr objectAtIndex:indexPath.row];
    //头像切圆
    [cell.releasePensonPicImageView sd_setImageWithURL: [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP,[dic valueForKey:@"headImage"]]]];
    cell.releasePensonPicImageView.layer.masksToBounds = YES;
    cell.releasePensonPicImageView.layer.cornerRadius = 38;
    
    cell.releaseTimeLB.text = [dic valueForKey:@"releaseTime"];
    cell.releasePersonNameLB.text = [dic valueForKey:@"nickname"];
    NSString *strAddress = [dic valueForKey:@"releaseAddress"];
    @try {
        if (!strAddress || [strAddress rangeOfString:@"null"].length > 0 || strAddress.length == 0) {
            strAddress = [User defaultUser].pStrLocationAddress;
        }
        cell.releaseAddressLB.text = strAddress;
    } @catch (NSException *exception) {
    } @finally {
    }
    
    cell.userAgeLB.text = [dic valueForKey:@"userAge"];
    [self setReleasePersonCellPayType:[dic valueForKey:@"payType"] movieDetailCell:cell];
    [self setreleasePersonCellSexImage:[dic valueForKey:@"userSex"] movieDetailCell:cell];
    float dist      = [[dic valueForKey:@"dist"] floatValue];
    cell.distLB.text    = [NSString stringWithFormat:@"%.2fkm", dist / 1000];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)setReleasePersonCellPayType:(NSString *)type movieDetailCell:(MovieDetailCell *)cell {
    switch ([type intValue]) {
        case 1:
            cell.payTypeImageView.image = [UIImage imageNamed:@"treat_me"];
            break;
        case 2:
            cell.payTypeImageView.image = [UIImage imageNamed:@"treat_you"];
            break;
        case 3:
            cell.payTypeImageView.image = [UIImage imageNamed:@"treat_AA"];
            break;
    }
}
-(void)setreleasePersonCellSexImage:(NSString *)sex movieDetailCell:(MovieDetailCell *)cell{

    switch ([sex intValue]) {
        case 1:
             cell.sexImageView.image = [UIImage imageNamed:@"sex_boy"];
             cell.userAgeLB.textColor = [UIColor colorWithRed:65.0/255 green:180.0/255 blue:255.0/255 alpha:1];
            break;
        case 2:
             cell.sexImageView.image = [UIImage imageNamed:@"sex_girl"];
             cell.userAgeLB.textColor = [UIColor colorWithRed:255.0/255 green:79.0/255 blue:59.0/255 alpha:1];
            break;
            }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic =  [self.dataArr objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"idfDateDetailVC" sender:dic];
}



#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"idfPublishDateVC"]) {
        
        PublishDateVC *publishVC = segue.destinationViewController;
        publishVC.movie_DateSate = em_release_movie_Date;
        publishVC.movie = self.movie;
    } else if([segue.identifier isEqualToString:@"idfDateDetailVC"]) {
        DateDetailVC *publishVC = segue.destinationViewController;
        publishVC.pDict = sender;
    }
}
@end
